package me.zhengjie.modules.web.rest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.config.entity.ResponseBaseEntity;
import me.zhengjie.config.enums.AtmrErrorEnum;
import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Feedback;
import me.zhengjie.modules.system.domain.UserFamilyMembers;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.FeedbackService;
import me.zhengjie.modules.system.service.UserFamilyMembersService;
import me.zhengjie.modules.system.service.dto.DictDetailDto;
import me.zhengjie.modules.system.service.dto.FeedbackDto;
import me.zhengjie.modules.system.service.dto.UserFamilyMembersDto;
import me.zhengjie.modules.system.service.dto.UserFamilyMembersQueryCriteria;
import me.zhengjie.modules.web.domain.ModifyMobileRequest;
import me.zhengjie.modules.web.domain.PersonalCenterResponse;
import me.zhengjie.modules.web.service.IPersonalCenterService;
import me.zhengjie.modules.web.service.mybatisplus.IUserFamilyMembersPlusService;
import me.zhengjie.request.ATMRContext;
import me.zhengjie.service.LocalStorageService;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
 * 个人中心
 */
@RestController
@RequestMapping("web/personal")
@Api(tags = "前端接口-个人中心")
public class PersonalCenterController {

    @Autowired
    private IPersonalCenterService personalCenterService;

    @Autowired
    FeedbackService feedbackService;

    @Autowired
    LocalStorageService localStorageService;

    @Autowired
    UserFamilyMembersService userFamilyMembersService;

    @Autowired
    DictDetailService dictDetailService;

    @Autowired
    private IUserFamilyMembersPlusService userFamilyMembersPlusService;
    /**
     * 我的页面
     * @return
     */
    @PostMapping("center")
    @ApiOperation("个人中心接口")
    public ResponseBaseEntity center(){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            if (StringUtils.isBlank(openId)){
                throw new WeChatException("openId is null");
            }
            PersonalCenterResponse centerResponse = personalCenterService.userCenter(openId);
            response.setBody(centerResponse);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            e.printStackTrace();
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }


    @PostMapping("/feeback")
    @ApiOperation("新增反馈建议")
    public ResponseBaseEntity createFeedback(@RequestParam("openId") String openId, @Validated @RequestBody Feedback resources){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            if (StringUtils.isBlank(openId)){
                throw new WeChatException("openId is null");
            }
            FeedbackDto centerResponse = feedbackService.create(resources);
            response.setBody(centerResponse);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }


    @PostMapping("/pictures")
    @ApiOperation("上传图片")
    public ResponseBaseEntity upload(@RequestParam("file") MultipartFile file){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            // 判断文件是否为图片
            String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
            if(!FileUtil.IMAGE.equals(FileUtil.getFileType(suffix))){
                throw new BadRequestException("只能上传图片");
            }
            LocalStorage localStorage = localStorageService.create(null, file);
            response.setBody(localStorage);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @PostMapping("/modifyUserInfo")
    @ApiOperation("WEB-修改用户信息")
    public ResponseBaseEntity modifyUserInfo(@RequestBody ModifyMobileRequest requestEntity){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            requestEntity.setOpenId(ATMRContext.getContext().getOpenId());
            if (StringUtils.isAnyBlank(requestEntity.getMobile(),requestEntity.getOpenId(),requestEntity.getCode())){
                throw new WeChatException("缺少参数");
            }
            boolean result = personalCenterService.modifyMobile(requestEntity);
            response.setBody(result);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @PostMapping("/createWxUser_other")
    @ApiOperation("其他应用调用，获取用户信息")
    public ResponseBaseEntity createWxUser_other(@RequestBody ModifyMobileRequest requestEntity){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            if (StringUtils.isAnyBlank(requestEntity.getMobile(),requestEntity.getOpenId())){
                throw new WeChatException("缺少参数");
            }
            boolean result = personalCenterService.createWxUser_other(requestEntity);
            response.setBody(result);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @PostMapping("/family")
    @ApiOperation("新增家庭成员")
    public ResponseBaseEntity createFamilyMembers(@Validated @RequestBody UserFamilyMembers member){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            member.setOpenId(openId);
            if (StringUtils.isBlank(openId)){
                throw new WeChatException("openId is null");
            }
            member.setCreateTime(DateUtil.TimestampNow());
            UserFamilyMembersDto userFamilyMembersDto = userFamilyMembersService.create(member);
            response.setBody(userFamilyMembersDto);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @PostMapping("/query/family")
    @ApiOperation("查询家庭成员")
    public ResponseBaseEntity queryFamilyMembers(){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            if (StringUtils.isBlank(openId)){
                throw new WeChatException("openId is null");
            }
            UserFamilyMembersQueryCriteria criteria = new UserFamilyMembersQueryCriteria();
            criteria.setOpenId(openId);
            List<UserFamilyMembersDto> userFamilyMembersDtoList = userFamilyMembersService.queryAll(criteria);
            if (CollectionUtils.isNotEmpty(userFamilyMembersDtoList)){
                userFamilyMembersDtoList.forEach(s -> {
                    String memberRole = s.getMemberRole();
                    if ("daughter".equalsIgnoreCase(memberRole)){
                        s.setMemberRoleName("女儿");
                    }else if ("son".equalsIgnoreCase(memberRole)){
                        s.setMemberRoleName("儿子");
                    }
                });
            }
            response.setBody(userFamilyMembersDtoList);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @PutMapping("/family")
    @ApiOperation("更新家庭成员")
    public ResponseBaseEntity modifyFamilyMembers(@Validated @RequestBody UserFamilyMembers member){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            member.setOpenId(openId);
            if (StringUtils.isBlank(openId) || Objects.isNull(member.getMemberId())){
                throw new WeChatException("缺少参数");
            }
            member.setUpdateTime(DateUtil.TimestampNow());
            UserFamilyMembers members = new UserFamilyMembers();
            members.setMemberAge(member.getMemberAge());
            members.setMemberRole(member.getMemberRole());
            members.setUserName(member.getUserName());
            members.setMemberSex(member.getMemberSex());
            members.setUpdateTime(DateUtil.TimestampNow());
            LambdaQueryWrapper<UserFamilyMembers> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserFamilyMembers::getOpenId,openId);
            wrapper.eq(UserFamilyMembers::getMemberId,member.getMemberId());
            boolean update = userFamilyMembersPlusService.update(members,wrapper);
            response.setBody(update);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }
    @DeleteMapping("/family")
    @ApiOperation("删除家庭成员")
    public ResponseBaseEntity delFamilyMembers(@Validated @RequestBody UserFamilyMembers member){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            member.setOpenId(openId);
            if (StringUtils.isBlank(openId) || Objects.isNull(member.getMemberId())){
                throw new WeChatException("openId is null");
            }
            LambdaQueryWrapper<UserFamilyMembers> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserFamilyMembers::getOpenId,openId);
            wrapper.eq(UserFamilyMembers::getMemberId,member.getMemberId());
            boolean remove = userFamilyMembersPlusService.remove(wrapper);
            response.setBody(remove);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }
    @GetMapping("/query/dict")
    @ApiOperation("查询查询数据字典")
    public ResponseBaseEntity queryDictDetail(@RequestParam("type") String type){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            /*String openId = ATMRContext.getContext().getOpenId();
            if (StringUtils.isBlank(openId)){
                throw new WeChatException("openId is null");
            }*/
            if (StringUtils.isBlank(type)){
                throw new WeChatException("type is null");
            }
            List<DictDetailDto> dictDetailDtoList = dictDetailService.getDictByName(type);
            response.setBody(dictDetailDtoList);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }
}
